package com.kjlink.internal.workreport.group.controller;

import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.model.PageInfo;
import cn.xuqiudong.common.base.model.Remind;
import cn.xuqiudong.common.base.vo.Select2VO;
import cn.xuqiudong.common.util.CommonUtils;
import com.kjlink.internal.workreport.base.controller.BaseController;
import com.kjlink.internal.workreport.group.model.Group;
import com.kjlink.internal.workreport.group.service.GroupService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * 功能: :小组 控制层
 *
 * @author Vic.xu
 * @since 2024-04-29 13:40
 */
@RestController
@RequestMapping("/group")
public class GroupController extends BaseController<GroupService, Group> {


    /**
     * 全部的小组
     */
    @RequestMapping(value = "all")
    public BaseResponse<List<Select2VO>> all() {
        Group lookup = new Group();
        lookup.setEnable(true);
        List<Group> list = service.list(lookup);
        List<Select2VO> result = CommonUtils.listFilter(list, group -> new Select2VO(group.getId(), group.getName()));
        return BaseResponse.success(result);
    }


    /**
     * 列表页
     */
    @RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView index(Group lookup) {
        ModelAndView modelAndView = new ModelAndView("group/list");
        PageInfo<Group> pager = service.page(lookup);
        pager.setLookup(lookup);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    /**
     * 前往新增页面
     */
    @GetMapping("/form")
    public ModelAndView insert() {
        ModelAndView mv = new ModelAndView("group/form");
        return mv;
    }

    /**
     * 前往新增页面
     */
    @GetMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable Integer id, RedirectAttributes attrs) {

        Group entity = service.findById(id);
        if (entity == null) {
            attrs.addAttribute(Remind.danger().setMessage("不存在的小组"));
            return new ModelAndView("redirect:/group/");
        }
        ModelAndView mv = new ModelAndView("group/form");
        mv.addObject("entity", entity);
        return mv;
    }

    @RequestMapping("/checkName")
    public BaseResponse<Boolean> checkName(Integer id, String name) {
        boolean success = service.checkNotRepeat(id, name, "name");
        return BaseResponse.success(success);
    }

    @PostMapping("/save")
    public ModelAndView save(Group entity, RedirectAttributes attrs) {
        ModelAndView mv = new ModelAndView("redirect:/group/");
        service.save(entity);
        attrs.addFlashAttribute(Remind.success().setMessage("保存成功"));
        return mv;
    }

    @Override
    protected String home() {
        return "/group/";
    }
}
